package pro1.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pro1.dao.CharacterModuleMapper;
import pro1.dao.ModuleMapper;
import pro1.model.Module;
import pro1.model.ResponseBody;
import pro1.service.ModuleService;

@Service
public class ModuleServiceImpl implements ModuleService {

	@Autowired
	ModuleMapper moduleMapper;

	@Autowired
	CharacterModuleMapper characterModuleMapper;

	@Override
	public ResponseBody all(Integer chaId) {
		if (chaId == null) {
			return new ResponseBody(1, "成功", moduleMapper.selectAll());
		}
		return new ResponseBody(1, "成功", moduleMapper.selectAllByCharacterId(chaId));
	}

	@Override
	public ResponseBody addOrUpdate(Integer chaId, String name, String path, String info) {
		ResponseBody response = new ResponseBody(1, "成功");
		if (chaId == null) {
			Module cha = moduleMapper.selectByName(name);
			if (cha == null) {
				cha = new Module();
				cha.setName(name);
				cha.setPath(path);
				cha.setInfo(info);
				moduleMapper.insertSelective(cha);
			} else {
				response = new ResponseBody(0, "该权限已存在");
			}
		} else {
			Module cha = moduleMapper.selectByPrimaryKey(chaId);
			if (cha == null) {
				response = new ResponseBody(0, "该权限不存在");
			} else {
				cha.setName(name);
				cha.setPath(path);
				cha.setInfo(info);
				moduleMapper.updateByPrimaryKeySelective(cha);
			}
		}
		return response;
	}

	@Override
	public ResponseBody delete(Integer chaId) {
		ResponseBody response = new ResponseBody(1, "成功");
		Module cha = moduleMapper.selectByPrimaryKey(chaId);
		if (cha == null) {
			response = new ResponseBody(0, "该权限不存在");
		} else {
			moduleMapper.deleteByPrimaryKey(chaId);
			characterModuleMapper.deleteByModuleId(chaId);
		}
		return response;
	}
}
